﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using PH.Model.Schools;
using System.Text.RegularExpressions;
using Utils;
namespace PH.Data.Schools
{
    public class StudentCommand
    {
        public static void SaveCheck(StudentModel model, DBCentre db)
        {
            if (string.IsNullOrEmpty(model.RealName))
                throw new Utils.PhException("请提供学生姓名");
            if (model.NationID < 1 || model.NationID > 58)
                throw new Utils.PhException("民族代码无效");
            if (!string.IsNullOrEmpty(model.Mobile))
            {
                if (!Regex.IsMatch(model.Mobile,@"^\d{11,12}$"))
                    throw new Utils.PhException("请提供正确的手机号码");
            }
            if (string.IsNullOrEmpty(model.StudentNo))
                throw new Utils.PhException("请提供身份证号码");

            if (db != null)
            {
                var dClass = db.DataContext.Classes.FirstOrDefault(p => p.ID == model.ClassID);
                if (dClass != null)
                {
                    model.SchoolID = dClass.SchoolID;
                    model.GradeCode = dClass.GradeCode;
                    model.ClassName = dClass.ClassName;
                    if (new int[] { 21, 31, 41 }.Contains(model.GradeCode))
                    {
                        if (string.IsNullOrEmpty(model.OriSchoolCode))
                            throw new Utils.PhException("请提供原毕业学校编码");
                        if (!db.DataContext.Schools.Any(p => p.Code == model.OriSchoolCode))
                            throw new Utils.PhException("无效的原毕业学校编码");
                    }
                }
                else
                    throw new Utils.PhException("班级不存在。");

                //var school = db.DataContext.Schools.FirstOrDefault(p => p.ID == model.SchoolID);
                if (!dClass.Chinese)
                {
                    if (db.DataContext.Students.Any(p => p.StudentNo == model.StudentNo && p.SchoolID==model.SchoolID && p.Guid != model.Guid))
                        throw new Utils.PhException("该身份证号码已存在");
                }
                else
                {
                    if (!model.StudentNo.CheckIDNo())
                        throw new Utils.PhException("请提供正确的身份证号码");
                    var sexBit = int.Parse(model.StudentNo.Substring(16, 1)) % 2;
                    if ((model.Sex - 1) == sexBit)
                        throw new PhException("身份证号码与学生性别不符。");
                    var oStu = db.DataContext.Students.FirstOrDefault(p => p.StudentNo == model.StudentNo && p.Guid != model.Guid);
                    if (oStu != null)
                    {
                        if (oStu.School.ID == model.SchoolID)
                            throw new Utils.PhException("该身份证号码已存在");
                        else
                        {
                            var sUser = oStu.School.Users.FirstOrDefault(p => p.Roles.Any(o => o.RoleName == "SchoolAdmin"));
                            string mess = string.Format("该身份证号码的学生，目前档案在{0}。请联系该校删除该学生后再导入。", oStu.School.SchoolName);
                            if (sUser != null)
                                mess += string.Format(" 联系方式：{0} {1}", sUser.RealName, sUser.Mobile);
                            throw new Utils.PhException(mess);
                        }
                    }
                }
            }
        }

        public static StudentModel CreateNewStudent(StudentModel model)
        {
            if (model != null)
            {
                model.CreatedOn = DateTime.Now;
                model.Guid = Guid.NewGuid();
                model.Status = (int)Model.Status.Active;
                using (DBCentre db = new DBCentre())
                {
                    SaveCheck(model, db);

                    //if (db.DataContext.Students.Any(p=>p.StudentNo==model.StudentNo && p.SchoolID==model.SchoolID))
                    //    throw new Utils.PhException("学生的身份证号重复");
                    var dStudent = Convertor.ConvertFrom<Student, StudentModel>(model);
                    db.DataContext.Students.Add(dStudent);
                    db.DataContext.SaveChanges();

                    model.ID = dStudent.ID;
                    return model;
                }
            }
            return null;
        }

        public static void UpdateStudent(StudentModel model)
        {
            if (model != null && model.Guid!=Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var dStudent = db.DataContext.Students.FirstOrDefault(p => p.Guid==model.Guid);
                    if (dStudent != null)
                    {
                        SaveCheck(model, db);

                        #region 如果修改班级，同年级的则改成绩表中的班级，不同年级删除成绩
                        if (model.ClassID != dStudent.ClassID)
                        {
                            if (model.GradeCode == dStudent.GradeCode)
                            {
                                var lst = db.DataContext.Marks.Where(p => p.StudentID == dStudent.ID).ToList();
                                if (lst != null && lst.Count > 0)
                                {
                                    lst.ForEach(p =>
                                    {
                                        p.ClassID = model.ClassID;
                                        p.ClassName = model.ClassName;
                                    });
                                }
                            }
                            else
                                db.Delete<Mark>(p => p.StudentID == dStudent.ID);
                        }
                        #endregion


                        Convertor.UpdateValue(model, dStudent);
                        db.DataContext.SaveChanges();
                    }
                    else
                        throw new Utils.PhException("不存在的学生");
                }
            }
        }

        public static StudentModel GetStudent(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var dStudent = db.DataContext.Students.FirstOrDefault(p => p.Guid == guid);
                    if (dStudent != null)
                    {
                        var model = Convertor.ConvertTo<StudentModel, Student>(dStudent);
                        model.ClassName = dStudent.Class.ClassName;
                        return model;
                    }
                }
            }
            return null;
        }

        public static StudentCollection GetStudents(StudentQuery sea)
        {
            var result = new StudentCollection();
            using (DBCentre db = new DBCentre())
            {
                IQueryable<Student> q = db.DataContext.Students;
                if (sea != null)
                {
                    if (!string.IsNullOrEmpty(sea.Key))
                        q = q.Where(p => p.RealName.Contains(sea.Key) || p.StudentNo == sea.Key);
                    if (sea.SchoolGuid != Guid.Empty)
                        q = q.Where(p => p.School.Guid == sea.SchoolGuid);
                    if (sea.ClassGuid != Guid.Empty)
                        q = q.Where(p => p.Class.Guid == sea.ClassGuid);
                    if (sea.GradeCode > 0)
                        q = q.Where(p => p.GradeCode == sea.GradeCode);
                    if (sea.GradeStep == 1)
                        q = q.Where(p => p.GradeCode < 21);
                    else if (sea.GradeStep == 2)
                        q = q.Where(p => p.GradeCode >= 21);
                        
                }
                var n = q.Count();
                if (n > 0)
                {
                    q = q.OrderByDescending(p => p.ID);
                    if (sea != null && sea.PageSize > 0)
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    var lst = q.ToList();
                    result = Convertor.ConvertCollection<StudentModel, Student, StudentCollection>(lst);
                    result.TotalRecordsCount = n;
                    foreach (var stu in result)
                    {
                        var d = lst.FirstOrDefault(p => p.ID == stu.ID);
                        var dcla = d.Class;
                        stu.ClassName = dcla.ClassName;
                        stu.ClassIndex = dcla.CIndex;
                    }
                }
            }
            return result;
        }

        public static void DeleteStudent(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    db.Delete<Student>(p => p.Guid == guid);
                    db.DataContext.SaveChanges();
                    //var dStu = db.DataContext.Students.FirstOrDefault(p => p.Guid == guid);
                    //if (dStu != null)
                    //{
                    //    dStu.Status = (int)Model.Status.Delete;
                    //    db.DataContext.SaveChanges();
                    //}
                }
            }
        }

        public static StudentModel GetStudent(string studentNo)
        {
            if (!string.IsNullOrEmpty(studentNo))
            {
                using (DBCentre db = new DBCentre())
                {
                    var q = db.DataContext.Students.Where(p => p.StudentNo == studentNo);
                    var d = q.FirstOrDefault();
                    if (d != null)
                    {
                        var ret = Convertor.ConvertTo<StudentModel, Student>(d);
                        return ret;
                    }
                }
            }
            return null;
        }

        public static void ChangeIDNO(StudentModel model)
        {
            if (model != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.Students.FirstOrDefault(p => p.ID == model.ID && p.RealName == model.RealName && p.SchoolID == model.SchoolID);
                    if (d == null) throw new PhException("学生信息不正确");
                    if (model.StudentNo.CheckIDNo())
                    {
                        var sexBit = int.Parse(model.StudentNo.Substring(16, 1)) % 2;
                        if (d.Sex - 1 != sexBit)
                            d.StudentNo = model.StudentNo;
                        else
                            throw new PhException("身份证号码与学生性别不符。");
                    }
                    else
                        throw new PhException("身份证号码无效");
                    db.DataContext.SaveChanges();
                }
            }
        }

        public static void RemoveStudent(Guid classGuid)
        {
            if (classGuid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    db.Delete<Student>(p => p.Class.Guid == classGuid);
                    db.DataContext.SaveChanges();
                }
            }
        }
    }
}
